package io.renren.controller;


import io.renren.entity.SysOssEntity;

import io.renren.service.SysOssService;
import io.renren.utils.*;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.util.Date;
import java.util.List;
import java.util.Map;


/**
 * 文件上传
 * 
 * @author chenshun
 * @email sunlightcs@gmail.com
 * @date 2017-03-25 12:13:26
 */
@RestController
@RequestMapping("sys/upload")
public class SysUploadController extends AbstractController {
	@Autowired
	private SysOssService sysOssService;
	@Autowired
	private HttpServletRequest request;
	@Autowired
	private HttpServletResponse response;
	private final static String KEY = ConfigConstant.CLOUD_STORAGE_CONFIG_KEY;
	
	/**
	 * 列表
	 */
	@RequestMapping("/list")
	@RequiresPermissions("sys:upload:all")
	public R list(@RequestParam Map<String, Object> params){
		//查询列表数据
		Query query = new Query(params);
		List<SysOssEntity> sysOssList = sysOssService.queryList(query);
		int total = sysOssService.queryTotal(query);
		
		PageUtils pageUtil = new PageUtils(sysOssList, total, query.getLimit(), query.getPage());
		
		return R.ok().put("page", pageUtil);
	}
	/**
	 * 上传文件
	 */
	@RequestMapping(value ="/upload", method = RequestMethod.POST,headers={"Content-Type=multipart/form-data"})
	@RequiresPermissions("sys:upload:all")
	public R upload(@RequestParam("file") MultipartFile file) {
		String fileId =request.getParameter("fileId");
		String filePath ="";
		// 判断文件是否为空
		if (!file.isEmpty()) {
			if(file.getSize()>10240000)
			{
				throw new RRException("上传失败：文件大小不能超过10M");
			}
			try {
				//提取后缀
				String postfix = file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf("."));
				;
				// 文件保存路径
				filePath = request.getSession().getServletContext().getRealPath("/") + "upload\\"+getUser().getUsername()+"_"
						+ DateUtils.format(new Date(),"yyyyMMddHHmmss")+postfix;
				File saveDir = new File(filePath);

				//判断目标文件所在的目录是否存在
				if(!saveDir.getParentFile().exists()) {
					//如果目标文件所在的目录不存在，则创建父目录
					saveDir.getParentFile().mkdirs();
				}
				// 转存文件
				file.transferTo(saveDir);
			} catch (Exception e) {
				e.printStackTrace();
			}
		}else{
			throw new RRException("上传失败:请添加上传文件！");
		}

		//保存文件信息
		SysOssEntity ossEntity = new SysOssEntity();
		ossEntity.setUrl(filePath);
		ossEntity.setCreateDate(new Date());
		ossEntity.setFileName(file.getOriginalFilename());
		ossEntity.setUrlType("0");
		ossEntity.setFileId(fileId);
		sysOssService.save(ossEntity);

		return R.ok().put("url", filePath).put("fileId",ossEntity.getId());
	}


	/**
	 * 删除
	 */
	@RequestMapping("/delete")
	@RequiresPermissions("sys:upload:all")
	public R delete(@RequestBody Long[] ids){
	    for(int i=0;i<ids.length;i++){
			SysOssEntity ossEntity = sysOssService.queryObject(Long.valueOf(ids[i]));
            String url = ossEntity.getUrl();
            new File(url).delete();
        }
		sysOssService.deleteBatch(ids);

		return R.ok();
	}
	/**
	 * 下载
	 */
	@RequestMapping("/download")
	@RequiresPermissions("sys:upload:all")
	public R download() {
		try {
			String id = request.getParameter("id");
			SysOssEntity ossEntity = sysOssService.queryObject(Long.valueOf(id));
			String url = ossEntity.getUrl();
			//提取后缀
            String postfix = url.substring(url.lastIndexOf("."));
			//设置文件MIME类型
			response.setContentType(request.getSession().getServletContext().getMimeType(url));
			//设置Content-Disposition
			response.setHeader("Content-Disposition", "attachment;filename=" +DateUtils.format(new Date(),"yyyyMMddHHmmss")+postfix);
			//读取目标文件，通过response将目标文件写到客户端
			File file = new File(url);
			if (!file.exists()){
				throw new RRException("系统找不到指定的文件。");
			}
			//读取文件
			InputStream in = new FileInputStream(file);
			OutputStream out = response.getOutputStream();
			byte[] buf = new byte[1024];
			int len=0;
			while((len = in.read(buf)) != -1 ){
				out.write(buf,0,len);
			}
			in.close();
			out.flush();
			out.close();
		}catch (Exception e) {
			e.printStackTrace();
		}
		return R.ok();
	}
}
